#include "pch.h"
#include "FileReader.h"
#include "GaojieDriveApp.h"
#include "CloudManager.h"

CFileReader::CFileReader(const CF_CALLBACK_INFO *pCallbackInfo, LockExit lockExit, std::wstring strFileName)
	: m_bCanceled(false)
	, m_cfCbWrapper(pCallbackInfo)
	, m_lockExit(std::move(lockExit))
	, m_strFileName(std::move(strFileName))
	, m_nFileSize(0)
{
}

CFileReader::~CFileReader()
{
	assert(m_lockExit);

	GetApp()->GetCloudManager()->RemoveTask(GetKey());
}

INT64 CFileReader::GetKey() const
{
	return m_cfCbWrapper.GetTransferKey();
}

void CFileReader::Cancel()
{
	m_bCanceled = true;
}

void CFileReader::OnOpen(INT64 nFileSize, FILETIME ftLastWrite)
{
	AssertInOrderedTask();

	if (m_bCanceled)
		return;

	m_nFileSize = nFileSize;
}

void CFileReader::OnRead(BufferPtr pBuffer, INT64 nOffset, size_t nLength)
{
	AssertInOrderedTask();

	if (m_bCanceled)
		return;

	m_cfCbWrapper.ReportProgress(m_strFileName, m_nFileSize, nOffset);
	m_cfCbWrapper.TransferData(m_strFileName, pBuffer, nOffset, nLength);
}

void CFileReader::OnError(INT64 nOffset, INT64 nLength)
{
	AssertInOrderedTask();

	if (m_bCanceled)
		return;

	m_cfCbWrapper.TransferData(m_strFileName, nullptr, nOffset, nLength);
}
